package com.novel.system.controller;

import cn.hutool.core.io.FileUtil;
import com.novel.common.exception.file.FileException;
import com.novel.common.exception.file.IllegalFileException;
import com.novel.common.utils.StringUtils;
import com.novel.framework.base.BaseController;
import com.novel.framework.config.ProjectConfig;
import com.novel.framework.result.Result;
import com.novel.framework.utils.file.FileUploadUtils;
import com.novel.framework.utils.file.FileUtils;
import com.novel.framework.utils.file.ResourceLoaderUtils;
import com.novel.framework.web.config.ServerConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotBlank;
import java.io.BufferedOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.HashMap;

/**
 * 文件处理接口
 *
 * @author novel
 * @date 2019/5/24
 */
@RestController
@RequestMapping("/resources")
@Slf4j
public class FileController extends BaseController {
    /**
     * 文件上传路径
     */
    private static final String FILE_PATH = "/resources/file/";

    private final ServerConfig serverConfig;


    public FileController(ServerConfig serverConfig) {
        this.serverConfig = serverConfig;
    }


    /**
     * 通用上传请求
     */
    @PostMapping("/upload")
    public Result uploadFile(@RequestParam("file") @RequestBody MultipartFile file) {
        try {
            // 上传文件路径
            String filePath = ProjectConfig.getProfile();
            // 上传并返回新文件名称
            String fileName = FileUploadUtils.upload(filePath, file);
            fileName = FILE_PATH + fileName;
            String url = serverConfig.getUrl() + fileName;
            HashMap<String, Object> ajax = new HashMap<>(2);

            ajax.put("fileName", fileName);
            //url 如果在ie中，https网站无法直接访问，会被直接墙
            //解决办法就是把后端的服务也变成https网站，或者是通过nginx代理设置，但是ie还是会抛出错误
            ajax.put("url", url);
            return toAjax(ajax);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }


    /**
     * 查看文件
     *
     * @param request
     * @param response
     */
    @RequestMapping(value = "/file/**")
    public void download(HttpServletRequest request, HttpServletResponse response) {
        String url = request.getRequestURI().substring(16);
        response.addHeader("Cache-Control", "max-age=604800");
        BufferedOutputStream buff = null;
        try {
            buff = new BufferedOutputStream(response.getOutputStream());
            byte[] bytes = ResourceLoaderUtils.readBytes(url);
            if (bytes != null) {
                buff.write(bytes);
            }
            buff.flush();
        } catch (IOException e) {
            e.printStackTrace();
            log.error(e.getMessage());
        } finally {
            if (buff != null) {
                try {
                    buff.close();
                } catch (IOException e) {
                    e.printStackTrace();
                    log.error(e.getMessage());
                }
            }
        }
    }


    /**
     * 通用下载请求
     *
     * @param fileName 文件名称
     * @param delete   是否删除
     */
    @GetMapping("/download")
    public Result fileDownload(@NotBlank(message = "文件名不能为空") String fileName, @RequestParam(required = false, defaultValue = "false") Boolean delete, HttpServletResponse response, HttpServletRequest request) {
        try {
            if (!FileUtils.isValidFilename(fileName)) {
                throw new IllegalFileException(StringUtils.format("文件名称({})非法，不允许下载。 ", fileName));
            }
            String realFileName = System.currentTimeMillis() + fileName.substring(fileName.indexOf("_") + 1);
            String filePath = ProjectConfig.getDownloadPath() + fileName;
            if (!FileUtil.exist(filePath)) {
                throw new FileNotFoundException("文件不存在");
            }
            response.setCharacterEncoding("utf-8");
//            response.setContentType("multipart/form-data");
            response.setHeader("Content-Disposition", "attachment;fileName=" + FileUtils.setFileDownloadHeader(request, realFileName));
            FileUtils.writeBytes(filePath, response.getOutputStream());
            if (delete) {
                FileUtils.deleteFile(filePath);
            }
        } catch (FileException e) {
            log.error("下载文件失败", e);
            return error(e.getMessage());
        } catch (Exception e) {
            log.error("下载文件失败", e);
            return error("下载文件失败");
        }
        return error("下载文件失败");
    }

}
